<?php defined('SYSPATH') or die('No direct script access.');

class Controller_Home extends Controller
{
    //todo: add to config
    private $filePrefix = 'pr_';
    private $uploadDir = 'img/upload/';
    private $pageSize = 12;

    public function action_index()
    {
        //$this->response->body('hello, world!');
        $this->response->body(View::factory('index')->set('img_path', URL::base() . $this->uploadDir)->set('c_path', URL::base() . 'home/imglist'));
    }

    public function action_list()
    {
        $this->response->body('list!');
    }

    public function action_imglist()
    {
        /*if(! request::is_ajax()) {
            Event::run( 'system.404' );
        } */
        $totalRecords = ORM::factory('image')->count_all();

        $current = arr::get($_GET, 'page', 1);
        if (!Valid::digit($current))
            $current = 1;
        $total = ceil($totalRecords / $this->pageSize);
        $next = $current < $total ? $current + 1 : null;
        $previous = $current <= $total & $current > 1 ? $current - 1 : null;
        $offset = ($current - 1) * $this->pageSize;

        $image_result = ORM::factory('image')->order_by('created', 'desc')->limit($this->pageSize)->offset($offset)->find_all();

        $images = array();
        foreach ($image_result as $img) {
            $images[] = array('file_name' => $img->img_name, 'pr_file_name' => $this->filePrefix . $img->img_name, 'description' => $img->description);
        }

        $response = array(
            "images" => $images,
            "pager" => array('current' => $current, 'total' => $total, 'next' => $next, 'previous' => $previous, 'offset' => $offset));

        echo json_encode($response);
    }
}
